﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Write.API.Command.ApplyCommand;
using MediatR;

namespace B.S.BaseData.Read.API.CommandHandler.ApplyHandler
{
    public class DelAppBYIdCommandHandler : IRequestHandler<DelAppBYIdCommand, APIResult<List<Apply>>>
    {
        private readonly IBaseRepository<Apply> _baseRepository;
        private readonly IBaseRepository<RecordSheet> _RecordRepository;

        public DelAppBYIdCommandHandler(IBaseRepository<Apply> baseRepository, IBaseRepository<RecordSheet> recordRepository)
        {
            _baseRepository = baseRepository;
            _RecordRepository = recordRepository;
        }

        public async Task<APIResult<List<Apply>>> Handle(DelAppBYIdCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<Apply>> result = new APIResult<List<Apply>>();
            result.Code = APIEnum.Success;
            result.Msg = "删除成功";

            // 查询要删除的实体
            var entity = _baseRepository.GetAll().FirstOrDefault(p => p.ApplyId == request.ApplyId);
            var record = _RecordRepository.GetAll().FirstOrDefault(p => p.ApplyId == request.ApplyId);
            if (entity != null&&record!=null)
            {
                // 执行删除操作
                _baseRepository.Del(entity);
                _RecordRepository.Del(record);
            }
            else
            {
                result.Code = APIEnum.Failed; 
                result.Msg = "未找到要删除的申请记录";
            }

            return await Task.FromResult(result);
        }

    }
}
